<template>
  <div class="app-container">
    <el-form :inline="true" :model="userQuery" class="demo-form-inline">
      <el-form-item label="名字">
        <el-select v-model="userQuery.name" filterable clearable placeholder="输入名字">
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.name"
            :value="user.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工号">
        <el-select v-model="userQuery.workId" filterable clearable placeholder="输入工号">
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.workId"
            :value="user.workId">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="userQuery.status" style="margin-left: 10px;width: 80%" placeholder="请选择">
          <el-option
            v-for="status in statusEnum"
            :key="status.value"
            :label="status.label"
            :value="status.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>

    <el-button type="primary" @click="handleAddUser">创建新用户</el-button>

    <el-table :data="userList" style="width: 100%;margin-top:30px;" border>
      <el-table-column type="expand">
        <template #default="props">
          <!--{{ scope.row.name }}-->
          <el-form  class="demo-table-expand" inline label-position="left">
            <el-form-item label="角色">
              <span v-for="role in props.row.roles">
                {{ role }}
              </span>
            </el-form-item>
            <el-form-item label="名字"><span>{{ props.row.name }}</span></el-form-item>
            <el-form-item label="邮箱"><span>{{ props.row.email }}</span></el-form-item>
            <el-form-item label="电话"><span>{{ props.row.phone }}</span></el-form-item>
            <el-form-item label="个人简介"><span>{{ props.row.introduction }}</span></el-form-item>
            <el-form-item label="工号"><span>{{ props.row.workId }}</span></el-form-item>
            <el-form-item label="工龄"><span>{{ props.row.workAge }}</span></el-form-item>
            <el-form-item label="部门"><span>{{ props.row.department }}</span></el-form-item>
            <el-form-item label="上级"><span>{{ props.row.boss }}</span></el-form-item>
            <el-form-item label="职位"><span>{{ props.row.position }}</span></el-form-item>
            <el-form-item label="等级"><span>{{ props.row.level }}</span></el-form-item>
            <el-form-item label="状态"><span>
              <el-select v-model="props.row.status" style="margin-left: 10px;width: 40%" disabled>
                <el-option
                  v-for="status in statusEnum"
                  :key="status.value"
                  :label="status.label"
                  :value="status.value">
                </el-option>
              </el-select>
            </span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="工号" prop="workId"></el-table-column>
      <el-table-column label="名字" prop="name"></el-table-column>
      <el-table-column label="部门" prop="department"></el-table-column>

      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-select v-model="scope.row.status" style="margin-left: 10px;width: 40%" placeholder="请选择"
                     @change="changeStatus(scope)">
            <el-option
              v-for="status in statusEnum"
              :key="status.value"
              :label="status.label"
              :value="status.value">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
    </el-table>

    <div class="block">
      <!-- 分页 -->
      <el-pagination
        :current-page="page"
        :page-size="limit"
        :total="total"
        style="padding: 30px 0; text-align: center;"
        layout="total, prev, pager, next, jumper"
        @current-change="getUsers"
      />
    </div>

    <!--隐藏表单-->
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'Edit user':'New user'">
      <el-form :model="user" label-width="80px" label-position="left">
        <el-form-item label="名字">
          <el-input v-model="user.name" placeholder="名字"/>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="user.email" placeholder="邮箱"/>
        </el-form-item>
        <el-form-item label="工龄">
          <el-input v-model="user.workAge" placeholder="工龄"/>
        </el-form-item>
        <el-form-item label="部门">
            <el-cascader
              v-model="user.departmentId"
              placeholder="试试搜索：智能部"
              :options="departmentList"
              :props="SetCustomDept"
              clearable
              filterable></el-cascader>
        </el-form-item>
        <el-form-item label="职位">
          <el-select v-model="user.positionId" filterable placeholder="请选择职位">
            <el-option
              v-for="position in positionList"
              :key="position.id"
              :label="position.name"
              :value="position.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="等级">
          <el-select v-model="user.levelId" filterable placeholder="请选择等级">
            <el-option
              v-for="level in levelList"
              :key="level.id"
              :label="level.level"
              :value="level.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色" v-if="dialogType==='edit'">
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <div style="margin: 15px 0;"></div>
          <el-checkbox-group v-model="checkedRoles" @change="handleCheckedRolesChange">
            <el-checkbox v-for="role in roleList" :label="role.id" :key="role.id">{{role.nameZh}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmUser">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUsers, addUser, modifyStatus, modifyUser, getUserList } from '@/api/user'
import { deepClone } from '@/utils'
import { getDepartments } from '@/api/department'
import { getPositions } from '@/api/position'
import { getLevels } from '@/api/level'
import { addUserRole, getRoles } from '@/api/role'

const defaultUser = {
  id: '',
  name: '',
  username: '',
  avatar: '',
  email: '',
  phone: '',
  telephone: '',
  introduction: '',
  workId: '',
  workAge: '',
  departmentId: '',
  bossId: '',
  positionId: '',
  levelId: '',
  status: '',
  roles: [],
  roleIds: []
}
const checkedRoles = ['admin']

export default {
  name: 'userList',
  comments: {},
  created() {
    // Mock: get all routes and users list from server
    this.getUsers()
    this.getPositions()
    this.getLevels()
    this.getDepartments()
    this.getRoles()
  },
  data() {
    return {
      user: Object.assign({}, defaultUser),
      userList: [],
      positionList: [],
      levelList: [],
      departmentList: [],
      userInfoList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      total: 100,
      page: 1,
      limit: 20,
      userQuery: {},
      SetCustomDept: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true
      },
      roleList: [],
      checkAll: false,
      checkedRoles: [],
      isIndeterminate: true,
      statusEnum: [
        {value: 'ACTIVE', label: "有效"},
        {value: 'DELETED', label: "注销"},
        {value: 'BANNED', label: "禁用"}
      ]
    }
  },
  computed: {

  },
  methods: {
    onSubmit() {
      this.getUsers()
    },
    async getUsers(page = 1) {
      const offset = this.limit * (page - 1);
      const res = await getUsers(this.userQuery, offset, this.limit)
      this.userList = res.data.rows
      this.total = res.data.total
    },
    async getRoles() {
      const res = await getRoles()
      this.roleList = res.data.rows
    },
    async getPositions() {
      const res = await getPositions()
      this.positionList = res.data
    },
    async getLevels() {
      const res = await getLevels()
      this.levelList = res.data
    },
    async getDepartments() {
      await getDepartments(-1).then(res=>{
        // 调用递归方法，去除级联数据后将数据赋值给级联选择器
        this.departmentList=res.data
      });
    },
    async getUserList() {
      const res = await getUserList()
      this.userInfoList = res.data
    },
    handleAddUser() {
      this.user = Object.assign({}, defaultUser)
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    handleEdit(scope) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.user = deepClone(scope.row)
      this.checkedRoles = this.user.roleIds
      this.$nextTick(() => {
        // set checked state of a node not affects its father and child nodes
        this.checkStrictly = false
      })
    },
    async confirmUser() {
      const isEdit = this.dialogType === 'edit'
      if (isEdit) {
        const val = this.user.departmentId
        this.user.departmentId = !isNaN(val) || typeof(val) == "undefined"? val : val.pop()
        await modifyUser(this.user.id, this.user)
        await addUserRole(this.user.id, this.checkedRoles)
        for (let index = 0; index < this.userList.length; index++) {
          if (this.userList[index].id === this.user.id) {
            this.userList.splice(index, 1, Object.assign({}, this.user))
            break
          }
        }
      } else {
        const val = this.user.departmentId
        this.user.departmentId = !isNaN(val) ? val : val.pop()
        await addUser(this.user)
      }
      this.dialogVisible = false
      await this.getUsers()
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: "操作成功",
        type: 'success'
      })
    },
    handleCheckAllChange(val) {
      this.checkedRoles = this.roleList;
      this.isIndeterminate = false;
    },
    handleCheckedRolesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.roleList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.roleList.length;
      this.checkedRoles = value
    },
    changeStatus({ $index, row }){
      this.$confirm('确定要修改这个用户的状态吗?', 'Warning', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await modifyStatus(row.id, row.status)
          // this.userList.splice($index, 1)
          this.$message({
            type: 'success',
            message: '修改状态成功!'
          })
        })
        .catch(err => {
          console.error(err)
        })
    }
  }
}
</script>

<style scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
</style>
